package com.chixing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chixing.entity.Message;
import com.chixing.entity.UserMessage;
import com.chixing.mapper.MessageMapper;
import com.chixing.mapper.UserMessageMapper;
import com.chixing.service.IUserMessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chixing.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户消息关系表（含消息推送状态） 服务实现类
 * </p>
 *
 * @author smith
 * @since 2025-10-28
 */
@Service
public class UserMessageServiceImpl  implements IUserMessageService {

    @Autowired
    private UserMessageMapper userMessageMapper;
    @Autowired
    private MessageMapper messageMapper;

    @Override
    public Result getByUserId(Long userId) {
        //查询用户所有消息，并按时间降序排列
        QueryWrapper<UserMessage> userMessageQueryWrapper = new QueryWrapper<>();
        userMessageQueryWrapper.eq("user_id",userId).orderByDesc("created_at");
        List<UserMessage> userMessages = userMessageMapper.selectList(userMessageQueryWrapper);
        //封装消息模板
        List<Map<String , Object>> resultList = new ArrayList<>();
        for (UserMessage userMessage:userMessages) {
            QueryWrapper<Message> messageQueryWrapper = new QueryWrapper<>();
            messageQueryWrapper.eq("message_id", userMessage.getMessageId()); // 假设 messageId 对应 message 表的 code 字段
            Message message = messageMapper.selectOne(messageQueryWrapper);
            Map<String, Object> messageMap = new HashMap<>();
            messageMap.put("title",message.getTitle());
            messageMap.put("content",message.getContent());
            messageMap.put("sendTime",userMessage.getCreatedAt());
            messageMap.put("msgStatus",userMessage.getStatus());
            messageMap.put("msgId",userMessage.getId());
            resultList.add(messageMap);
        }
        if (resultList!=null&&resultList.size()>0)
            return Result.getSuccess(resultList);
        return Result.getFail(null);
    }

    @Override
    public Result updateMsgStatus(Long id) {
        int rows = userMessageMapper.updateMsgStatus(id);
        if (rows>0)
            return Result.updateSuccess(rows);
        return Result.updateFail(null);
    }
}
